package com.bricker.laboratorymanagement.business.socket;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bricker.laboratorymanagement.business.entity.Message;
import com.bricker.laboratorymanagement.business.service.MessageService;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;


@ServerEndpoint(value = "/message/{userId}")
@Component
public class MessageServer {

    private MessageService messageService;

    private static ApplicationContext applicationContext;

    private Session session;

    private String userId;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        MessageServer.applicationContext = applicationContext;
    }

    //获取未读消息列表
    private List<Message> getMessageBystatus(String userId){
        messageService = applicationContext.getBean(MessageService.class);
        String idString=","+userId+",";
        List<Message> messages = messageService.list(Wrappers.<Message>lambdaQuery().eq(Message::getDelFlag,"0")
                .eq(Message::getStatus,"0")
                .orderByDesc(Message::getCreatedTime));
        List<Message> list =null;
        if(CollectionUtils.isNotEmpty(messages)){
            list=messages.stream().filter(x->(","+x.getReceivers()+",").indexOf(idString)!=-1).collect(Collectors.toList());
        }
        return list;

    }

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) throws IOException, InterruptedException {
        this.session = session;
        this.userId = userId;
        sendMessage(userId);
    }

    @OnMessage
    public void onMesaage(String userId) throws IOException {
        if ("serve".equals(userId)) {

        } else {
            List<Message> messages = getMessageBystatus(userId);
            String message = JSONObject.toJSONString(messages);
            this.session.getBasicRemote().sendText(message);
        }
    }

    private void sendMessage(String userId) throws IOException {
        List<Message> messages = getMessageBystatus(userId);
        String message = JSONObject.toJSONString(messages);
        this.session.getBasicRemote().sendText(message);
    }
}
